var messageStr = null;
var promptStr = null;

cc.Class({
    extends: cc.Component,

    properties: {
    
    },

    onLoad() {
        cc.Toast = this;
        this.loadCount = 0;
        this.msgBox = this.node.find('message');
        this.msgBox.parent = null;
        this.loadBox = this.node.find('loading');        
        this.loadBox.cascadeOpacity = false;
        this.loadBox.setLocalZOrder(10000);
        this.loadBox.on('touchstart', event => event.stopPropagation(), this);
        this.ring = this.loadBox.find('ringBox').find('ring');
    },

    loading(show) {
        if(show) {
            this.unschedule(this.cancelLoading);
            this.scheduleOnce(this.cancelLoading, 10);
            this.loadCount++;
            if(this.loadCount > 1) return;
            this.loadBox.x = 0;
            this.ring.rotation = 0;
            this.schedule(this.updateLoading, 0.1);
        } else {
            this.loadCount = Math.max(this.loadCount - 1, 0);
            if(this.loadCount > 0) return;
            this.loadBox.x = 10000;
            this.unschedule(this.updateLoading);
            this.unschedule(this.cancelLoading);
        }
    },

    cancelLoading() {
        this.loadCount = 0;
        this.loadBox.x = 10000;
        this.unschedule(this.updateLoading);
    },

    updateLoading() {
        this.ring.rotation -= 360 / 8;
    },

    message(msg) {
        if(messageStr == msg) return;
        var box = cc.instantiate(this.msgBox);
        var txt = box.find('text', cc.Label);
        messageStr = msg;
        txt.string = msg;
        box.parent = this.node;
        box.x = 0;
        box.opacity = 0;
        box.runAction(cc.sequence(
            cc.fadeIn(0.3),
            cc.delayTime(1.5),
            cc.fadeOut(0.5), 
            cc.callFunc(() => { box.parent = null; messageStr = null; })));
    },

    prompt(msg) {
        if(promptStr == msg) return;
        var box = cc.instantiate(this.msgBox);
        var txt = box.find('text', cc.Label);
        var lyt = box.getComponent(cc.Layout);
        lyt.paddingTop = lyt.paddingBottom = 80;
        promptStr = msg;
        txt.string = msg;
        txt.fontSize = 40;
        txt.lineHeight = 50;
        box.parent = this.node;
        box.x = 0;
        box.y = 0;
        box.opacity = 0;
        box.runAction(cc.sequence(
            cc.fadeIn(0.3),
            cc.delayTime(1.5),
            cc.fadeOut(0.5), 
            cc.callFunc(() => { box.parent = null; promptStr = null; })));
    }, 
});
